package com.ideaaedi.springcloud.jd.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ideaaedi.springcloud.jd.commonds.constant.BaseConstant;
import com.ideaaedi.springcloud.jd.commonds.constant.JdSymbolConstant;
import com.ideaaedi.springcloud.jd.commonds.entity.BaseCodeMsgEnum;
import com.ideaaedi.springcloud.jd.commonds.entity.PageInfo;
import com.ideaaedi.springcloud.jd.commonds.entity.user.dto.DeptIdPostIdDTO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysDeptPO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysUserDeptPostRePO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysUserHisPO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysUserPO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysUserRoleRePO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.PhoneUpdateReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysUserAddReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysUserBindDeptPostReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysUserBindRolesReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysUserListReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysUserUpdateReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysQueryUserRoleRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysUserDetailRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysUserListRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.UserDeptPostInfoRespVO;
import com.ideaaedi.springcloud.jd.commonds.enums.user.CertTypeEnum;
import com.ideaaedi.springcloud.jd.commonds.enums.user.UserTypeEnum;
import com.ideaaedi.springcloud.jd.commonds.event.NeedAddHisEvent;
import com.ideaaedi.springcloud.jd.commonds.event.NeedDeleteHisEvent;
import com.ideaaedi.springcloud.jd.commonds.event.user.SysUserAddedEvent;
import com.ideaaedi.springcloud.jd.commonds.event.user.SysUserDeletedEvent;
import com.ideaaedi.springcloud.jd.commonds.event.user.SysUserUpdatedEvent;
import com.ideaaedi.springcloud.jd.commonds.exception.BaseException;
import com.ideaaedi.springcloud.jd.commonspring.config.properties.TenantProperties;
import com.ideaaedi.springcloud.jd.commonspring.mybatisplus.ServiceImplExt;
import com.ideaaedi.springcloud.jd.commonspring.mybatisplus.tenant.TenantProvider;
import com.ideaaedi.springcloud.jd.commonspring.support.CommonService;
import com.ideaaedi.springcloud.jd.commonspring.util.JdContextUtil;
import com.ideaaedi.springcloud.jd.commonspring.validator.ValidId;
import com.ideaaedi.springcloud.jd.commonspring.validator.ValidTenant;
import com.ideaaedi.springcloud.jd.user.mapper.SysUserMapper;
import com.ideaaedi.springcloud.jd.user.service.SysDeptService;
import com.ideaaedi.springcloud.jd.user.service.SysRoleService;
import com.ideaaedi.springcloud.jd.user.service.SysTenantService;
import com.ideaaedi.springcloud.jd.user.service.SysUserDeptPostReService;
import com.ideaaedi.springcloud.jd.user.service.SysUserRoleReService;
import com.ideaaedi.springcloud.jd.user.service.SysUserService;
import com.ideaaedi.springcloud.jd.user.support.UserCheckSupport;
import com.ideaaedi.springcloud.jd.user.util.SysUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统-用户表  (内部员工表) 服务实现类
 * </p>
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.1.A
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImplExt<SysUserMapper, SysUserPO> implements SysUserService,
        ApplicationRunner {
    
    @Resource
    private SysUserRoleReService sysUserRoleReService;
    
    @Resource
    private SysRoleService sysRoleService;
    
    @Resource
    private SysUserDeptPostReService sysUserDeptPostReService;
    
    @Resource
    private SysDeptService sysDeptService;
    
    @Resource
    private SysTenantService sysTenantService;
    
    @Resource
    private CommonService commonService;
    
    @Resource
    private TenantProperties tenantProperties;
    
    @Resource
    private UserCheckSupport userCheckSupport;
    
    private PasswordEncoder passwordEncoder;
    
    @Override
    public PageInfo<SysUserListRespVO> list(SysUserListReqVO req) {
        IPage<SysUserPO> pageInfo = new Page<>(req.getPageNum(), req.getPageSize());
        IPage<SysUserListRespVO> page = baseMapper.list(pageInfo, req);
        
        // 填充 业务tenantName
        List<SysUserListRespVO> records = page.getRecords();
        Set<String> tenantSet = records.stream()
                .filter(Objects::nonNull)
                .map(SysUserListRespVO::getTenant).collect(Collectors.toSet());
        Map<String, String> tenantAndNameMap = sysTenantService.mappingTenantName(tenantSet, true);
        for (SysUserListRespVO record : records) {
            record.setTenantName(tenantAndNameMap.get(record.getTenant()));
        }
        return PageInfo.of(page.getTotal(), req.getPageNum(), req.getPageSize(), records);
    }
    
    @Override
    public SysUserDetailRespVO detail(Long userId) {
        Objects.requireNonNull(userId, "userId cannot be null.");
        // 用户
        SysUserPO po = getOne(new LambdaQueryWrapper<SysUserPO>()
                .eq(SysUserPO::getId, userId)
        );
        if (po == null) {
            return null;
        }
        return detail(po);
    }
    
    @Override
    @ValidTenant
    @Transactional(rollbackFor = Exception.class)
    public SysUserDetailRespVO update(SysUserUpdateReqVO req) {
        String password = req.getPassword();
        String certNo = req.getCertNo();
        CertTypeEnum certType = req.getCertType();
        String accountNo = req.getAccountNo();
        Long id = req.getId();
        String phone = req.getPhone();
        Set<Long> roleIds = req.getRoleIds();
        List<DeptIdPostIdDTO> deptPostList = req.getDeptPostList();
        String tenant = req.getTenant();
        UserTypeEnum type = req.getType();
        // 原来的po
        SysUserPO oldPo = getById(id);
        if (oldPo == null) {
            throw new BaseException("user id -> " + id, BaseCodeMsgEnum.DATA_NON_EXIST_OR_NON_DATA_PERMISSION);
        }
        if (StringUtils.isBlank(tenant)) {
            tenant = oldPo.getTenant();
        }
        if (type == null) {
            type = oldPo.getType();
        }
        
        // 账号相关校验
        if (StringUtils.isNotBlank(accountNo)) {
            // 特殊字符检验
            userCheckSupport.checkAccountNoSpecialCharacter(accountNo);
            // 全局校验，账号是否已经被占用
            boolean accountUsed = ifAccountExist(accountNo, id) != null;
            if (accountUsed) {
                throw new BaseException(BaseCodeMsgEnum.ACCOUNT_NO_IS_OCCUPIED, accountNo);
            }
        }
        // 同租户校验，手机号是否已经被占用
        if (StringUtils.isNotBlank(phone)) {
            userCheckSupport.checkExistSamePhone(tenant, type, phone, id);
        }
        // 同租户校验，证件号是否已经被占用
        if (certType != null && StringUtils.isNotBlank(certNo)) {
            userCheckSupport.checkExistSameCert(tenant, type, certType, certNo, id);
        }
    
        // 插入用户信息
        SysUserPO po = new SysUserPO();
        BeanUtils.copyProperties(req, po, BaseConstant.TENANT);
        if (StringUtils.isNotBlank(password)) {
            po.setPassword(passwordEncoder.encode(password));
        }
        po.setTenant(tenant);
        // 如果手机号修改了，那么将原来的微信openId清空
        String oldPhone = oldPo.getPhone();
        if (phone != null && !phone.equals(oldPhone)) {
            po.setWechatOpenId(BaseConstant.EMPTY);
        }
        updateById(po);
        SysUserPO newPo = getById(id);
        
        // 绑定角色
        if (roleIds != null) {
            SysUserBindRolesReqVO bindDeptPostReq = new SysUserBindRolesReqVO();
            bindDeptPostReq.setUserId(id);
            bindDeptPostReq.setRoleIds(roleIds);
            bindRole(bindDeptPostReq);
        }
        // 绑定部门和职位
        if (deptPostList != null) {
            SysUserBindDeptPostReqVO bindDeptPostReq = new SysUserBindDeptPostReqVO();
            bindDeptPostReq.setUserId(id);
            bindDeptPostReq.setDeptPostList(deptPostList);
            bindDeptPost(bindDeptPostReq);
        }
        // 发布事件
        applicationContext.publishEvent(new SysUserUpdatedEvent(oldPo, newPo));
        if (!Objects.equals(oldPo, newPo)) {
            applicationContext.publishEvent(new NeedAddHisEvent(Lists.newArrayList(newPo), SysUserHisPO.class));
        }
        return detail(id);
    }
    
    @Override
    @ValidTenant
    @Transactional(rollbackFor = Exception.class)
    public SysUserDetailRespVO add(SysUserAddReqVO req) {
        String password = req.getPassword();
        String certNo = req.getCertNo();
        String phone = req.getPhone();
        String accountNo = req.getAccountNo();
        CertTypeEnum certType = req.getCertType();
        Set<Long> roleIds = req.getRoleIds();
        UserTypeEnum type = req.getType();
        List<DeptIdPostIdDTO> deptPostList = req.getDeptPostList();
        String tenant = req.getTenant();
        if (StringUtils.isBlank(tenant)) {
            tenant = JdContextUtil.currUserTenantNonNull();
        }
    
        // 特殊字符检验
        userCheckSupport.checkAccountNoSpecialCharacter(accountNo);
        
        // 全局校验，账号是否已经被占用
        if (StringUtils.isNotBlank(accountNo)) {
            boolean accountUsed = ifAccountExist(accountNo, null) != null;
            if (accountUsed) {
                throw new BaseException(BaseCodeMsgEnum.ACCOUNT_NO_IS_OCCUPIED, accountNo);
            }
        } else {
            // 生成accountNo
            do {
                accountNo = RandomStringUtils.random(12, true, true);
            } while (ifAccountExist(accountNo, null) != null);
            log.info("generate accountNo -> {}", accountNo);
        }
        
        // 同租户校验，手机号是否已经被占用
        if (StringUtils.isNotBlank(phone)) {
            userCheckSupport.checkExistSamePhone(tenant, type, phone, null);
        }
        // 同租户校验，证件号是否已经被占用
        if (certType != null && StringUtils.isNotBlank(certNo)) {
            userCheckSupport.checkExistSameCert(tenant, type, certType, certNo, null);
        }
        
        // 插入用户信息
        long id = IdWorker.getId();
        SysUserPO po = new SysUserPO();
        BeanUtils.copyProperties(req, po, BaseConstant.TENANT);
        po.setId(id);
        po.setAccountNo(accountNo);
        po.setPassword(passwordEncoder.encode(password));
        po.setTenant(tenant);
        save(po);
        // 绑定角色
        if (roleIds != null) {
            SysUserBindRolesReqVO bindDeptPostReq = new SysUserBindRolesReqVO();
            bindDeptPostReq.setUserId(id);
            bindDeptPostReq.setRoleIds(roleIds);
            bindRole(bindDeptPostReq);
        }
        // 绑定部门和职位 同时设置用户的租户值
        if (deptPostList != null) {
            SysUserBindDeptPostReqVO bindDeptPostReq = new SysUserBindDeptPostReqVO();
            bindDeptPostReq.setUserId(id);
            bindDeptPostReq.setDeptPostList(deptPostList);
            bindDeptPost(bindDeptPostReq);
        }
    
        SysUserPO lastPo = getById(id);
        applicationContext.publishEvent(new SysUserAddedEvent(lastPo));
        applicationContext.publishEvent(new NeedAddHisEvent(Lists.newArrayList(lastPo), SysUserHisPO.class));
        return detail(lastPo);
    }
    
    @Override
    @ValidId
    @Transactional(rollbackFor = Exception.class)
    public SysUserDetailRespVO delete(Long userId, boolean fromAkSkDelete) {
        SysUserPO po = getById(userId);
        UserTypeEnum type = po.getType();
        if (!fromAkSkDelete && type == UserTypeEnum.CLIENT_AK_SK) {
            throw new BaseException(BaseCodeMsgEnum.DO_NOT_DELETE_AKSK_USER_HERE);
        }
        SysUserDetailRespVO resp = detail(po);
        // 删除用户
        update(new SysUserPO(), new LambdaUpdateWrapper<SysUserPO>()
                .set(SysUserPO::getDeleted, 1)
                .set(SysUserPO::getDeletedTime, System.currentTimeMillis() / 1000)
                .eq(SysUserPO::getId, userId)
        );
        // 发布事件
        applicationContext.publishEvent(new SysUserDeletedEvent(po));
        applicationContext.publishEvent(new NeedDeleteHisEvent(Lists.newArrayList(userId), SysUserHisPO.class));
        return resp;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysQueryUserRoleRespVO> bindRole(SysUserBindRolesReqVO req) {
        Long userId = req.getUserId();
        Set<Long> roleIds = req.getRoleIds();
        // 删除原来的
        sysUserRoleReService.remove(new LambdaQueryWrapper<SysUserRoleRePO>()
                .eq(SysUserRoleRePO::getUserId, userId)
        );
        
        // 添加新的
        if (roleIds != null) {
            List<SysUserRoleRePO> list = roleIds.stream().map(roleId -> {
                SysUserRoleRePO sysUserRoleRe = new SysUserRoleRePO();
                sysUserRoleRe.setId(IdWorker.getId());
                sysUserRoleRe.setRoleId(roleId);
                sysUserRoleRe.setUserId(userId);
                return sysUserRoleRe;
            }).collect(Collectors.toList());
            sysUserRoleReService.saveBatch(list);
        }
        return queryRole(userId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysQueryUserRoleRespVO> queryRole(Long userId) {
        Set<Long> roleIds = sysUserRoleReService.list(new LambdaQueryWrapper<SysUserRoleRePO>()
                .eq(SysUserRoleRePO::getUserId, userId)
        ).stream()
                .map(SysUserRoleRePO::getRoleId)
                .collect(Collectors.toSet());
        
        List<SysQueryUserRoleRespVO> list = Collections.emptyList();
        if (!CollectionUtils.isEmpty(roleIds)) {
            list = sysRoleService.listByIds(roleIds).stream().map(x -> {
                SysQueryUserRoleRespVO resp = new SysQueryUserRoleRespVO();
                resp.setCode(x.getCode());
                resp.setName(x.getName());
                resp.setRemark(x.getRemark());
                resp.setId(x.getId());
                return resp;
            }).collect(Collectors.toList());
        }
        return list;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<UserDeptPostInfoRespVO> bindDeptPost(SysUserBindDeptPostReqVO req) {
        Long userId = req.getUserId();
        List<DeptIdPostIdDTO> deptPostList = req.getDeptPostList();
        // 删除旧的
        sysUserDeptPostReService.update(new SysUserDeptPostRePO(), new LambdaUpdateWrapper<SysUserDeptPostRePO>()
                .set(SysUserDeptPostRePO::getDeleted, 1)
                .eq(SysUserDeptPostRePO::getUserId, userId)
        );
        
        // 绑定新的
        if (!CollectionUtils.isEmpty(deptPostList)) {
            List<SysUserDeptPostRePO> poList = deptPostList.stream().map(x -> {
                SysUserDeptPostRePO po = new SysUserDeptPostRePO();
                po.setId(IdWorker.getId());
                po.setUserId(userId);
                po.setDeptId(x.getDeptId());
                po.setPostId(x.getPostId());
                return po;
            }).collect(Collectors.toList());
            sysUserDeptPostReService.saveBatch(poList);
    
            // 插件用户主归属部门是否发生了变化
            Integer userMainDeptId = poList.get(0).getDeptId();
            SysDeptPO userMainDept = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptPO>()
                    .select(SysDeptPO::getTenant)
                    .eq(SysDeptPO::getId, userMainDeptId)
            );
            Objects.requireNonNull(userMainDept, "userMainDept should not be null.");
            String mainDeptTenant = userMainDept.getTenant();
    
            SysUserPO updatedUser = getOne(new LambdaQueryWrapper<SysUserPO>()
                    .select(SysUserPO::getTenant)
                    .eq(SysUserPO::getId, userId)
            );
            Objects.requireNonNull(updatedUser, "updatedUser should not be null.");
            String dbTenant = updatedUser.getTenant();
            if (!mainDeptTenant.equals(dbTenant)) {
                boolean update = update(new SysUserPO(), new LambdaUpdateWrapper<SysUserPO>()
                        .set(SysUserPO::getTenant, mainDeptTenant)
                        .eq(SysUserPO::getId, userId)
                );
                log.info("update user [{}] tenant from [{}] to [{}], result -> {}.", userId, dbTenant, mainDeptTenant, update);
            }
        }
        return queryDeptPost(userId);
    }
    
    @Override
    public List<UserDeptPostInfoRespVO> queryDeptPost(Long userId) {
        List<UserDeptPostInfoRespVO> list = this.baseMapper.listDeptPost(userId);
        // 处理 deptIdPath
        String tenant = JdContextUtil.currUserTenantNonNull();
        boolean isBelongBizTenant = sysTenantService.belongBizTenant(tenant);
        for (UserDeptPostInfoRespVO resp : list) {
            String deptIdPath = resp.getDeptIdPath();
            if (StringUtils.isBlank(deptIdPath)) {
                continue;
            }
            String path = SysUserUtil.shrinkDeptPathIfNecessary(tenant, isBelongBizTenant, tenantProperties.getBizTenantLevel(), Lists.newArrayList(deptIdPath)).get(deptIdPath);
            resp.setDeptNamePath(path);
        }
        
        // 处理 deptNamePath
        List<String> deptIdPathList = list.stream().map(UserDeptPostInfoRespVO::getDeptIdPath).collect(Collectors.toList());
        Map<String, String> pathNameMap = sysDeptService.mappingDeptNamePath(deptIdPathList);
        for (UserDeptPostInfoRespVO resp : list) {
            String deptIdPath = resp.getDeptIdPath();
            resp.setDeptNamePath(pathNameMap.get(deptIdPath));
        }
        return list;
    }
    
    @Override
    public SysUserDetailRespVO updatePhone(PhoneUpdateReqVO req) {
        final String phone = req.getPhone();
        final Long userId = req.getUserId();
        final SysUserPO existUser = getOne(new LambdaQueryWrapper<SysUserPO>()
                .eq(SysUserPO::getPhone, phone)
                .ne(SysUserPO::getId, userId)
                .last("limit 1")
        );
        if (existUser != null) {
            throw new BaseException(BaseCodeMsgEnum.SYSTEM_INTERNAL_DATA_NON_ALLOW_UPDATE);
        }
        
        update(new SysUserPO(), new LambdaUpdateWrapper<SysUserPO>()
                .set(SysUserPO::getPhone, phone)
                .set(SysUserPO::getWechatOpenId, null)
                .eq(SysUserPO::getId, userId)
        );
        return detail(userId);
    }
    
    @Override
    @Nullable
    public SysUserPO ifAccountExist(@NonNull String accountNo, @Nullable Long excludedId) {
        Objects.requireNonNull(accountNo, "accountNo cannot be null.");
        return TenantProvider.execGlobal(() -> this.getOne(
                        new LambdaQueryWrapper<SysUserPO>()
                                .eq(SysUserPO::getAccountNo, accountNo)
                                .ne(excludedId != null, SysUserPO::getId, excludedId)
                                .last("limit 1")
                ));
    }
    
    @Override
    public void run(ApplicationArguments args) {
        passwordEncoder = applicationContext.getBean(PasswordEncoder.class);
        Objects.requireNonNull(passwordEncoder, "passwordEncoder cannot be null.");
    }
    
    @NotNull
    private SysUserDetailRespVO detail(SysUserPO po) {
        Long userId = po.getId();
        // 用户拥有的角色
        List<Long> roles = sysUserRoleReService.list(new LambdaQueryWrapper<SysUserRoleRePO>()
                .eq(SysUserRoleRePO::getUserId, userId)
        ).stream().map(SysUserRoleRePO::getRoleId).collect(Collectors.toList());
        
        // 用户部门及职位职级信息
        final Map<Integer, String> deptIdAndNameMap =
                sysDeptService.list().stream().collect(Collectors.toMap(SysDeptPO::getId,
                        SysDeptPO::getName));
        final List<UserDeptPostInfoRespVO> deptPostList =
                sysUserDeptPostReService.list(new LambdaQueryWrapper<SysUserDeptPostRePO>()
                        .eq(SysUserDeptPostRePO::getUserId, userId)
                ).stream().map(sudp -> {
                    UserDeptPostInfoRespVO re = new UserDeptPostInfoRespVO();
                    final Integer deptId = sudp.getDeptId();
                    re.setUserId(userId);
                    re.setDeptId(deptId);
                    re.setPostId(sudp.getPostId());
                    final SysDeptPO currDept = sysDeptService.getById(deptId);
                    String deptIdPathWithoutRoot = currDept.getPath().replace(BaseConstant.GROUP_DEPT_ID + JdSymbolConstant.COMMA, "");
                    String deptNamePathWithoutRoot = Arrays.stream(deptIdPathWithoutRoot.split(JdSymbolConstant.COMMA))
                            .filter(StringUtils::isNotBlank)
                            .map(Integer::parseInt)
                            .map(deptIdAndNameMap::get)
                            .collect(Collectors.joining(","));
                    re.setDeptIdPath(deptIdPathWithoutRoot);
                    re.setDeptNamePath(deptNamePathWithoutRoot);
                    return re;
                }).collect(Collectors.toList());
        final SysUserDetailRespVO resp = new SysUserDetailRespVO();
        BeanUtils.copyProperties(po, resp);
        resp.setRoleIds(roles);
        resp.setDeptPostList(deptPostList);
        Long avatarId = po.getAvatarId();
        if (avatarId != null) {
            String avatarUrl = commonService.obtainFileIdUrl(avatarId + "").get(avatarId);
            resp.setAvatarUrl(avatarUrl);
        }
    
        // 用户所属租户
        String tenant = po.getTenant();
        if (StringUtils.isNotBlank(tenant)) {
            Map<String, String> tenantAndNameMap = sysTenantService.mappingTenantName(Sets.newHashSet(tenant), true);
            resp.setTenantName(tenantAndNameMap.get(tenant));
        }
        return resp;
    }
}
